#include <cstdint>
#include <iostream>
#include <cstdlib>
#include "comm_v1.h"

int ok_num = 0;
int err_num[PARSE_ERROR_TYPE_UNDEFINED + 1] = {0};

static uint32_t comm_v1_transmit_handler(const comm_v1_runtime_t *runtime, const uint8_t *data, uint32_t length)
{
    return 0;
}

static void  comm_v1_error_handler (const comm_v1_runtime_t *runtime, parse_error_type_t error_type)
{
    if (error_type != PARSE_ERROR_TYPE_SOF)
    {
        // printf("can%d com parse error: %d!\n", (int)runtime->line, error_type);
    }

    err_num[error_type] ++;
}


static void comm_v1_message_handler(const comm_v1_runtime_t *runtime,
            const comm_v1_header_t *header,const uint8_t *message, uint32_t length)
{
    // printf("can%d com parse ok!\n", (int)runtime->line);
    ok_num ++;
}


int main()
{
    comm_v1_config_t comm_v1_cfg;
    comm_v1_cfg.line = 0;
    comm_v1_cfg.id = 0;
    comm_v1_cfg.name = "f1";
    comm_v1_cfg.start_of_frame = 0x5A;
    comm_v1_cfg.max_message_length = 1024;
    comm_v1_cfg.message_handler = comm_v1_message_handler;
    comm_v1_cfg.transmit_handler = comm_v1_transmit_handler;
    comm_v1_cfg.parse_error_handler = comm_v1_error_handler;
    void *handle = comm_v1_create(&comm_v1_cfg);
    if(handle == NULL)
    {
        printf("create comm v1 handle error!\n");
    }

    uint8_t buf[11+768] = {
        0x5A, /* sof */
        230,  /* sender */
        0,    /* receiver */
        1,     /* seq */
        0x00, 0x17, /* mssgid */
        130,0, /* len */
        0,     /* chksum0 */
        0,0      /* chksum1 */
    };

    srand((unsigned)time(NULL));

    for (int i = 0; i < 100 * 1000 * 1000; i ++)
    {
        int r = rand();
        if (r > 0)
        {
            buf[0] = 0x5A;
        }
        else
        {
            buf[0] = r & 0xff;
        }
        ++ buf[3]; /* seq */
        uint16_t send_len = (r >> 8)& 0x1ff;
        buf[6] = send_len & 0xff;
        buf[7] = (send_len >> 8) & 0xff;
        buf[8] = 0;
        for (int j = 0; j < 8; j ++)
        {
            buf[8] += buf[j];
        };
        for (int j = 0; j < send_len; j ++)
        {
            buf[j + 9] = rand() & 0xff;
        }

        uint16_t chksum1 = 0;
        if (i % 10)
        {
            for (int j = 0; j < send_len + 9; j ++)
            {
                chksum1 += buf[j];
            }
        }
        else
        {
            chksum1 = rand() & 0xffff;
        }
        buf[send_len + 9] = chksum1 & 0xff;
        buf[send_len + 10] = (chksum1 >> 8) & 0xff;

        comm_v1_process(handle, buf, send_len + 12);
    }

    printf("test end !!!!!!!\n");
    printf("ok_num: %d\n", ok_num);
    for (int i = 0; i < PARSE_ERROR_TYPE_UNDEFINED + 1; i ++)
    {
        printf("err_num[%d]: %d\n", i, err_num[i]);
    }
}
